<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="70px"
    >
      <el-form-item label="任务名称" prop="workingName">
        <div style="width: 180px">
          <el-input
            v-model="queryParams.workingName"
            placeholder="请输入任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </div>
      </el-form-item>
      <el-form-item label="创建时间" prop="workingName">
        <el-date-picker
          v-model="queryParams.time"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          type="datetimerange"
          align="right"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '00:00:00']"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-button
      type="primary"
      style="margin-bottom: 10px"
      icon="el-icon-download"
      size="mini"
      :loading="btnLoading"
      @click="handleExport"
      v-hasPermi="['technology:technologyWorkingMaterial:export']"
      >导出</el-button
    >
    <el-button
      type="primary"
      icon="el-icon-thumb"
      style="margin-bottom: 10px"
      size="mini"
      @click="submitForm"
      v-hasPermi="['technology:technologyWorkingMaterial:save']"
      >保存</el-button
    >
    <el-row :gutter="20">
      <el-col :span="9">
        <el-table
          :cell-style="{ padding: this.tablePadding }"
          border
          v-loading="loading"
          :data="workingList"
          size="small"
          highlight-current-row
          @row-click="rowClick"
          :height="height"
          :row-key="getRowKeys"
          @selection-change="handleSelectionChange"
          ref="interfaceTable"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            :reserve-selection="true"
          />
          <!-- <el-table-column label="任务ID" align="center" prop="workingId" /> -->
          <el-table-column label="任务名称" align="center" prop="workingName" />
          <el-table-column label="开始时间" align="center" prop="startTime" />
          <el-table-column label="结束时间" align="center" prop="endTime" />
        </el-table>
        <pagination
          small
          v-show="total > 0"
          :total="total"
          layout="prev, pager, next"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
      <el-col :span="15">
        <el-card class="box-card">
          <div>
            <summary-box ref="summaryRef" />
          </div>
          <fixed-cost ref="fixedRef" @costChange="costChange" />
          <other-consumables ref="otherRef" @otherChange="costChange" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listWorking } from "@/api/technology/working";
import SummaryBox from "./components/Summary.vue";
import FixedCost from "./components/FixedCost.vue";
import OtherConsumables from "./components/OtherConsumables.vue";
import { setTechnologyWorkingMaterialCost } from "@/api/technology/cost";
export default {
  components: { SummaryBox, FixedCost, OtherConsumables },
  data() {
    return {
      height: document.documentElement.scrollHeight - 260 + "px",
      workingList: [],
      loading: false,
      btnLoading: false,
      workingId: null,
      total: 0,
      tableCheckbox: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: [],
        workingCategoryId: null,
        workingName: null,
        equipmentId: null,
        deptId: null,
        status: 1, //成功的任务
        technologyMaterialAddMethodId: null,
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getRowKeys(row) {
      return row.workingId;
    },
    handleSelectionChange(val) {
      this.tableCheckbox = val;
    },
    handleQuery() {
      if (this.queryParams.time.length > 0) {
        this.queryParams.startTime = this.queryParams.time[0];
        this.queryParams.endTime = this.queryParams.time[1];
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
      }
      this.queryParams.pageNum = 1;
      this.tableCheckbox=[]
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.time = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.loading = true;
      listWorking(this.queryParams).then((response) => {
        this.workingList = response.rows;
        this.$nextTick(function() {
        this.$refs.interfaceTable.setCurrentRow(this.workingList[0])
      })
        if (this.workingList.length > 0) {
          this.workingId = this.workingList[0].workingId;
          this.rowClick(this.workingList[0]);
          // 获取右侧详情
        } else {
          this.workingId = "";
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    rowClick(row) {
      this.workingId = row.workingId;
      this.$refs.fixedRef.getList(this.workingId);
      this.$refs.summaryRef.getInfo(this.workingId);
      this.$refs.otherRef.getList(this.workingId);
    },
    judgeObjectComplete(ObjectValue) {
      let flag = new Boolean();
      flag = true;
      for (let key in ObjectValue) {
        if (ObjectValue[key]) {
        } else {
          flag = false;
        }
      }
      if (!flag) {
        return false;
      } else {
        return true;
      }
    },
    judgeListComplete(list) {
      let isNotComplete = list.findIndex((item) => {
        return this.judgeObjectComplete(item) === false;
      });
      if (isNotComplete > -1) {
        return false;
      } else {
        return true;
      }
    },
    /** 提交按钮 */
    testForm(list, type) {
      let editList = JSON.parse(JSON.stringify(list));
      // 去除全部为空值的项
      for (var i in editList) {
        if (
          editList[i].otherMaterialName == "" &&
          editList[i].amount == "" &&
          editList[i].materialPrice == ""
        ) {
          editList[i] = "";
        }
      }
      // 排除全部值都没有填写的行
      let resList = editList.filter((element) => {
        return !element == "";
      });
      // 这里判断值是否输入有效。且全部输入
      let arrOther = resList.map((item, index) => {
        // 其他耗材才需要输入耗材名和单价
        return Object.assign(
          {},
          { otherMaterialName: type ? item.otherMaterialName : "1" },
          { amount: item.amount },
          { materialPrice: type ? item.materialPrice : "1" }
        );
      });
      let flag = false;
      flag = this.judgeListComplete(arrOther);

      if (!flag) {
        this.msgError("请检查输入的值是否有效！");
        return false;
      }
      return resList;
    },
    // 按钮提交
    submitForm() {
      let fixedList = this.$refs.fixedRef.list;
      let fRes = this.testForm(fixedList, 0);
      let oRes;
      if (fRes) {
        let otherList = this.$refs.otherRef.list;
        oRes = this.testForm(otherList, 1);
      }
      if (fRes && oRes) {
        let obj = {
          technologyWorkingMaterials: JSON.parse(JSON.stringify(fRes)),
          technologyWorkingMaterialOtherCosts: JSON.parse(JSON.stringify(oRes)),
          workingId: this.workingId,
        };
        setTechnologyWorkingMaterialCost(obj).then((res) => {
          this.msgSuccess("编辑成功");
          this.$refs.fixedRef.getList(this.workingId);
          this.$refs.summaryRef.getInfo(this.workingId);
          this.$refs.otherRef.getList(this.workingId);
        });
      }
    },
    costChange() {
      // 固定成本或者其他耗材变更后，重新请求汇总与固定耗材

      this.getSummary();
    },
    getSummary() {
      let arr = this.$refs.fixedRef.list.map((item, index) => {
        return Object.assign({}, { money: item.money });
      });
      let arrOther = this.$refs.otherRef.list.map((item, index) => {
        return Object.assign({}, { money: item.money });
      });
      let arrRes = [...arrOther, ...arr];
      let num = 0;
      arrRes.forEach((item) => {
        num = num + parseFloat(item.money);
      });
      // 总成本相加 end
      this.$refs.summaryRef.setDetails(num.toFixed(2));
    },
    handleExport() {
      this.btnLoading = true;
       let ids=this.tableCheckbox.map(item=>{
         return item.workingId
       })
       let query=JSON.parse(JSON.stringify(this.queryParams))
       query.workIds=ids
      this.download(
        "technology/technologyWorkingMaterial/exportAllCost",
        {
          ...query,
        },
        `exportAllCost_${new Date().getTime()}.xlsx`,
        "",
        () => {
          this.btnLoading = false;
        }
      );
    },
  },
};
</script>

<style>
/* .cost-border{
  border:2px solid #eee;
  padding:5px;

} */
</style>